﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using S.Produce.Infrastructure;
using System.Text;

namespace S.Produce.Read.Api.Extensions
{
    public static class ServiceCollectionExtensions
    {

        public static IServiceCollection AddRepository(this IServiceCollection services, string conn)
        {
            services.AddDbContext<MyDbContext>(x => x.UseSqlServer(conn));
            services.AddTransient(typeof(IRepository<>), typeof(BaseRepository<>));


            return services;
        }

        /// <summary>
        /// 注册JWT
        /// </summary>
        /// <param name="services"></param>
        /// <param name="builder"></param>
        public static void AddJWT(this IServiceCollection services, WebApplicationBuilder builder)
        {
            builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
            {
                //取出密钥
                var secretByte = Encoding.UTF8.GetBytes(builder.Configuration["Authentication:SecretKey"]);
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    //验证发布者
                    ValidateIssuer = true,
                    ValidIssuer = builder.Configuration["Authentication:Issuer"],
                    //验证接收者
                    ValidateAudience = true,
                    ValidAudience = builder.Configuration["Authentication:Audience"],
                    //验证是否过期
                    ValidateLifetime = true,
                    //验证私钥
                    IssuerSigningKey = new SymmetricSecurityKey(secretByte)
                };
            });
        }
    }
}
